import sys
import datetime
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sb
from PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout, QPushButton
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC





class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.init_ui()

    def init_ui(self):
        self.resize(1000, 500)
        # 解决无法显示中文
        plt.rcParams['font.sans-serif'] = ['SimHei']
        # 解决无法显示负号
        plt.rcParams['axes.unicode_minus'] = False
        # 按钮
        self.one_btn = QPushButton('画一条线')
        self.more_btn = QPushButton('重复画线')
        self.reset_btn = QPushButton('重置')
        # 按钮绑定方法
        self.one_btn.clicked.connect(self.draw_cmd)
        self.more_btn.clicked.connect(self.draw_cmd)
        self.reset_btn.clicked.connect(self.reset_cmd)
        # 设置画布部分
        self.fig = plt.figure(figsize=(10, 4), dpi=80)
        self.canvas = FC(self.fig)
        # 添加第一个图
        self.ax = self.fig.add_subplot('121')
        # self.ax.set_title('画一条线')
        self.ax.set_title('第一个人的')
        # 添加第二个图
        self.ax1 = self.fig.add_subplot('122')
        # self.ax1.set_title('重复画线')
        self.ax1.set_title('第二个人的')
        # 设置布局，将组件添加到布局中
        self.layout = QVBoxLayout()

        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.one_btn)
        self.layout.addWidget(self.more_btn)
        self.layout.addWidget(self.reset_btn)

        self.setLayout(self.layout)

    def draw_cmd(self):
        try:
            # 如果是点击画一条线的按钮，就先清除内容
            if self.sender() == self.one_btn:
                ax = self.ax
                # ax.cla()
                tncd=self.get_data()
                ax = sb.heatmap(tncd, cmap='YlOrBr', linewidths=.5, annot=True, fmt="d", square=True,
                                cbar_kws={"orientation": "vertical"})
                # self.ax.set_title('画一条线')


            # 如果是点击重复画图的按钮，就不清除原先的内容
            elif self.sender() == self.more_btn:
                ax = self.ax1
            # 绘图部分
            x = [i + 1 for i in range(5)]  # x轴
            y = np.random.randint(0, 10, 5)  # y轴
            ax.plot(x, y)  # 折线图
            self.canvas.draw()  # 绘制
        except Exception as e:
            print(e)

    def reset_cmd(self):
        try:
            # 清除内容
            self.ax.cla()
            self.ax1.cla()
            # 重新设置标题
            self.ax.set_title('画一条线')
            self.ax1.set_title('重复画线')
            # 重新绘制
            self.canvas.draw()
        except Exception as e:
            print(e)

    def delta_date(self, start_date, end_date):
        """
        计算起始与结束日期长度，是结束-起始，所以一般为正。用做判定日期大小需要注意前后顺序
        :param start_date:
        :param end_date:
        :return:
        """
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        delta_day = (end - start).days
        return delta_day

    def dateAdd(self,start_date,days):
        """
        最正确的日期加法
        :param start_date:
        :param days:
        :return:
        """
        d=datetime.datetime.strptime(start_date,'%Y-%m-%d')
        delta = datetime.timedelta(days=days)
        n_days = d + delta
        return (n_days.strftime('%Y-%m-%d'))

    def getEveryDay(self,start_date, end_date):
        date_list = []
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        while start <= end:
            date_str = start.strftime("%Y-%m-%d")
            date_list.append(date_str)
            start += datetime.timedelta(days=1)
        return date_list

    def clip_list(self,a,c):  #a为原列表，c为等分长度
        clip_back=[]
        if len(a)>c:
            for i in range(int(len(a) / c)):
                # print(i)
                clip_a = a[c * i:c * (i + 1)]
                clip_back.append(clip_a)
                # print(clip_a)
            # last 剩下的单独为一组
            last = a[int(len(a) / c) * c:]
            if last:
                clip_back.append(last)
        return clip_back

    def get_data(self):
        ori_today = datetime.datetime.today()
        today = ori_today.strftime("%Y-%m-%d")

        now = datetime.datetime.now()
        this_week_start = (now - datetime.timedelta(days=now.weekday())).strftime("%Y-%m-%d")
        this_week_end = (now + datetime.timedelta(days=6 - now.weekday())).strftime("%Y-%m-%d")
        last_last_last_week_start =self.dateAdd(this_week_start, -7 * 3)
        next_week_end = self.dateAdd(this_week_end, 7)
        all_dates = self.getEveryDay(last_last_last_week_start, next_week_end)
        print(all_dates)
        mo_data = [i for i in range(len(all_dates))]
        cs = self.clip_list(all_dates, 7)
        cd = self.clip_list(mo_data, 7)
        print(cs)
        ncs = np.array(cs)
        ncd = np.array(cd)
        tncs = ncs.T
        tncd = ncd.T
        return tncd


def start():
    app = QApplication(sys.argv)
    m = MyWidget()
    m.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    start()
